/*
 * Creative Commons Deed
 * Attribution-NonCommercial-ShareAlike 1.0 Finland
 * 
 * You are free:
 * 
 * * to copy, distribute, display, and perform the work
 * * to make derivative works
 * Under the following conditions:
 * 
 * Attribution. You must attribute the work in the manner specified by the author or licensor.
 * 
 * Noncommercial. You may not use this work for commercial purposes.
 * 
 * Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only 
 * under a license identical to this one.
 * 
 * * For any reuse or distribution, you must make clear to others the license terms of this work.
 * * Any of these conditions can be waived if you get permission from the copyright holder.
 * Your fair use and other rights are in no way affected by the above.
 * This is a human-readable summary of the Legal Code (the full license). 
 */
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;
using System.Threading;
using System.Collections.Specialized;
using System.Diagnostics;

namespace PocketLibrary.Storage
{
    [Obsolete]
    public class BoxNet
    {
        /**/
        public delegate void UpDownHandler(bool finished);
        public event UpDownHandler OnAlreadyTransferring;


        public delegate void TransferProgressHandler(FileTransferArgs args);
        //public event TransferProgressHandler OnTransfer;

        public event UploadProgressHandler OnUpload;
        public event UploadProgressHandler OnDownload;

        private static bool singleton = false;

        private static BoxNet instance = null;

        public string DownloadPath = "";

        BoxNet()
        {
            comm = new XMLRPCCommunication(BaseUrl + sid);
            comm.UseStringBuilder = false;
            comm.OnDownloadProgress += new UploadProgressHandler(comm_OnDownloadProgress);
            comm.OnUploadProgress += new UploadProgressHandler(comm_OnUploadProgress);
        }

        void comm_OnUploadProgress(object sender, UploadProgressEventArgs e)
        {
            if (OnUpload != null)
                OnUpload(this, e);
        }

        void comm_OnDownloadProgress(object sender, UploadProgressEventArgs e)
        {
            if (OnDownload != null)
                OnDownload(this, e);
        }

        public static BoxNet Create()
        {
            if (!singleton)
            {
                instance = new BoxNet();
                singleton = true;
                return instance;
            }
            else
                return instance;
        }

        void AlreadyTranferring()
        {
            if (OnAlreadyTransferring != null)
                OnAlreadyTransferring(false);
        }

        public string UserName = "";
        public string PassWord = "";
        public string Email = "";
        private string access_id = "";
        private string user_id = "";
        protected string sid = "";

        protected string fileid = "";
        protected string filename = "";
        protected long filesize = 0;

        protected string BaseUrl = "http://www.box.net/ping/";

        protected Thread downloadThread;
        bool transferring = false;
        protected bool downloadDone = false;

        protected XmlDocument sendXmlDoc = new XmlDocument();
        protected XmlDocument rcvXmlDoc = new XmlDocument();

        public XmlDocument ReceivedXml
        {
            get { return rcvXmlDoc; }
        }

        private bool fileResponse = false;

        public string SessionId
        {
            get { return sid; }
        }
        XMLRPCCommunication comm = null;


        /*
        void SendReceiveXml()
        {
            try
            {
                rcvXmlDoc = new XmlDocument();
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(BaseUrl + sid);

                req.Method = "POST";
                req.UserAgent = "TaskuBlogi 1.0";
                req.ContentType = "text/xml";

                byte[] data = Encoding.ASCII.GetBytes(sendXmlDoc.InnerXml);
                req.ContentLength = data.Length;
                Stream newstream = req.GetRequestStream();
                newstream.Write(data, 0, data.Length);
                newstream.Close();
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                Stream restream = res.GetResponseStream();

                StringBuilder sbb = new StringBuilder();

                using (StreamReader sr = new StreamReader(restream))
                {
                    while (sr.Peek() != -1)
                    {
                        sbb.Append(sr.ReadToEnd());
                    }
                }
                restream.Close();
                res.Close();
                rcvXmlDoc.LoadXml(sbb.ToString());
                ReceivedXml.LoadXml(sbb.ToString());
            }
            catch (WebException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (XmlException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /**/
        public void GetResponseFromFile(string filepath)
        {
            fileResponse = true;
            //ReceivedXml.Load(filepath);
            rcvXmlDoc.Load(filepath);
        }

        //private void DownloadFileBinary(string localFile, string downloadUrl, long size)
        //{
        //    try
        //    {
        //        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(downloadUrl);
        //        req.Method = "GET";
        //        req.UserAgent = "TaskuBlogi 1.0";

        //        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

        //        // Retrieve response stream
        //        Stream respStream = resp.GetResponseStream();

        //        // Create local file
        //        FileStream wrtr = new FileStream(localFile, FileMode.Create);

        //        // Allocate byte buffer to hold stream contents
        //        byte[] inData = new byte[4096];

        //        long transfered = 0;

        //        // loop through response stream reading each data block
        //        //  and writing to the local file
        //        int bytesRead = respStream.Read(inData, 0, inData.Length);
        //        while (bytesRead > 0)
        //        {
        //            wrtr.Write(inData, 0, bytesRead);
        //            bytesRead = respStream.Read(inData, 0, inData.Length);
        //            TransferChunk(size, transfered);
        //            transfered += bytesRead;
        //        }

        //        respStream.Close();
        //        wrtr.Close();
        //        TransferComplete(size, transfered);
        //        DownloadComplete();
        //    }
        //    catch (WebException)
        //    {
        //        DownloadComplete();
        //    }

        //}

        /*
        private void UploadFileBinary(string localFile, string uploadUrl)
        {
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uploadUrl);
                //req.Method = "PUT";
                req.Method = "POST";
                req.UserAgent = "TaskuBlogi 1.0";
                //req.ContentType = "multipart/form-data";
                //req.Headers.Add("location", "0");

                req.AllowWriteStreamBuffering = true;

                // Retrieve request stream 
                Stream reqStream = req.GetRequestStream();

                // Open the local file
                FileStream rdr = new FileStream(localFile, FileMode.Open);

                // Allocate byte buffer to hold file contents
                byte[] inData = new byte[4096];

                // loop through the local file reading each data block
                //  and writing to the request stream buffer
                int bytesRead = rdr.Read(inData, 0, inData.Length);
                while (bytesRead > 0)
                {
                    reqStream.Write(inData, 0, bytesRead);
                    bytesRead = rdr.Read(inData, 0, inData.Length);
                }

                rdr.Close();
                reqStream.Close();

                HttpWebResponse res = (HttpWebResponse)req.GetResponse();

            }
            catch { }
            finally
            {
                UploadComplete();
            }
        }
        /**/

        public bool Login()
        {

            sendXmlDoc = new XmlDocument();
            sendXmlDoc.LoadXml("<xml></xml>");
            XmlNode root = sendXmlDoc.DocumentElement;
            XmlElement action = sendXmlDoc.CreateElement("action");
            XmlText actiontxt = sendXmlDoc.CreateTextNode("authorization");

            XmlElement eleLogin = sendXmlDoc.CreateElement("login");
            XmlText xmlusername = sendXmlDoc.CreateTextNode(this.UserName);
            XmlElement elePassword = sendXmlDoc.CreateElement("password");
            XmlText xmlpassword = sendXmlDoc.CreateTextNode(this.PassWord);

            root.AppendChild(action);
            action.AppendChild(actiontxt);

            root.AppendChild(eleLogin);
            eleLogin.AppendChild(xmlusername);

            root.AppendChild(elePassword);
            elePassword.AppendChild(xmlpassword);

            //this.SendReceiveXml();

            comm.UploadString = sendXmlDoc.InnerXml;
            comm.Url = this.BaseUrl + sid;
            comm.SendReceive();
            rcvXmlDoc.LoadXml(comm.Response);

            XmlNodeList status = rcvXmlDoc.GetElementsByTagName("status");

            if (status.Count > 0)
            {
                if (status[0].InnerText == "\nlogged\n")
                {
                    XmlNodeList user = rcvXmlDoc.GetElementsByTagName("user");
                    this.sid = (user[0].SelectNodes("descendant::sid")).Item(0).InnerText;
                    this.Email = (user[0].SelectNodes("descendant::email")).Item(0).InnerText;
                    this.access_id = (user[0].SelectNodes("descendant::access_id")).Item(0).InnerText;
                    this.user_id = (user[0].SelectNodes("descendant::user_id")).Item(0).InnerText;
                    comm.Url = BaseUrl + sid;
                    return true;
                }
                else
                    return false;
            }
            return false;
        }

        public List<BoxNetFs> FileList()
        {
            return FileList("0");
        }

        public virtual List<BoxNetFs> FileList(string folder)
        {
            List<BoxNetFs> retval = new List<BoxNetFs>();
            sendXmlDoc = new XmlDocument();
            sendXmlDoc.LoadXml("<xml></xml>");

            XmlNode root = sendXmlDoc.DocumentElement;
            XmlElement action = sendXmlDoc.CreateElement("action");
            XmlText actiontxt = sendXmlDoc.CreateTextNode("account_tree");

            XmlElement xmlFolderId = sendXmlDoc.CreateElement("folder_id");
            XmlText xmlTFolderId = sendXmlDoc.CreateTextNode(folder);
            XmlNode xmlOneLevel = sendXmlDoc.CreateElement("one_level");
            XmlText xmlTOneLevel = sendXmlDoc.CreateTextNode("1");

            root.AppendChild(action);
            action.AppendChild(actiontxt);

            root.AppendChild(xmlFolderId);
            xmlFolderId.AppendChild(xmlTFolderId);

            root.AppendChild(xmlOneLevel);
            xmlOneLevel.AppendChild(xmlTOneLevel);

            comm.UploadString = sendXmlDoc.InnerXml;
            comm.SendReceive();
            rcvXmlDoc.LoadXml(comm.Response);


            XmlNodeList status = rcvXmlDoc.GetElementsByTagName("status");

            if (status.Count > 0)
            {
                if (status[0].InnerText == "listing_ok")
                {
                    // select folder nodes first
                    XmlNodeList folders = rcvXmlDoc.GetElementsByTagName("folder");
                    XmlNodeList files = rcvXmlDoc.GetElementsByTagName("file");

                    for (int i = 0; i < folders.Count; i++)
                    {
                        BoxNetFs xmlfolder = new BoxNetFs();
                        xmlfolder.FolderId = folders[i].Attributes["id"].Value;
                        xmlfolder.ItemId = folders[i].Attributes["id"].Value;
                        xmlfolder.Name = folders[i].Attributes["name"].Value;
                        xmlfolder.Shared = folders[i].Attributes["shared"].Value;
                        xmlfolder.SharedLink = folders[i].Attributes["shared_link"].Value;
                        xmlfolder.SessionId = this.sid;
                        xmlfolder.ItemType = FileSystemType.FolderType;
                        retval.Add(xmlfolder);
                    }

                    for (int i = 0; i < files.Count; i++)
                    {
                        BoxNetFs file = new BoxNetFs();
                        file.FileId = files[i].Attributes["id"].Value;
                        file.ItemId = files[i].Attributes["id"].Value;
                        file.FileName = files[i].Attributes["file_name"].Value;
                        file.Shared = files[i].Attributes["shared"].Value;
                        file.Size = files[i].Attributes["size"].Value;
                        file.ThumbNail = files[i].Attributes["thumbnail"].Value;

                        // HACK: small -> large
                        //bnFiles[i].ThumbNail = bnFiles[i].ThumbNail.Replace("/small_thumb/", "/large_thumb/");

                        file.Created = files[i].Attributes["created"].Value;
                        file.UpDated = files[i].Attributes["updated"].Value;
                        file.SessionId = this.sid;
                        file.ItemType = FileSystemType.FileType;
                        retval.Add(file);
                    }

                    return retval;
                }
                else return null;
            }
            else
                return null;
        }

        public void DownloadFile(BoxNetFs bnDownload, string downloadfilepath)
        {
            if (!transferring)
            {
                transferring = true;
                try
                {
                    comm.DownloadFile(downloadfilepath,
                        string.Format("http://www.box.net/ping/download/{0}/{1}", bnDownload.FileId, sid), long.Parse(bnDownload.Size));
                }
                catch (WebException)
                {
                    Debug.WriteLine("Error in file downloading");
                }
                finally
                {
                    transferring = false;
                }
            }
            else
                AlreadyTranferring();
        }

        public void UploadFile(string localFile, string targetFolder)
        {
            if (!transferring)
            {
                transferring = true;
                try
                {
                    UploadFileBeta(localFile, targetFolder);
                }
                catch (WebException)
                {
                    Debug.WriteLine("Error in file upload");
                }
                finally
                {
                    transferring = false;
                }
            }
            else
                AlreadyTranferring();
        }

        private static string ResolveMimeType(string fileName)
        {
            switch (Path.GetExtension(fileName))
            {
                case ".txt":
                    return "text/plain";
                case ".html":
                    return "text/html";
                case ".htm":
                    return "text/html";
                case ".jpg":
                    return "image/jpeg";
                case ".png":
                    return "image/png";
                case ".gif":
                    return "image/gif";
                default:
                    return "application/octet-stream";
            }
        }

        void UploadFileBeta(string localFile, string targetFolder)
        {
            NameValueCollection pars = new NameValueCollection();
            pars.Add("location", targetFolder);

            comm.UploadFile(localFile, pars);
            //string boundary = "TASKUBLOGI_MIME_" + DateTime.Now.ToString("yyyyMMddhhmmss");
            //HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(string.Format("http://www.box.net/ping/upload/{0}", sid));
            //req.Method = "POST";
            //req.KeepAlive = false;
            //req.Timeout = 50000;
            //req.ContentType = "multipart/form-data; boundary=\"" + boundary + "\"";
            //StringBuilder sb = new StringBuilder();

            //NameValueCollection parameters = new NameValueCollection();
            //parameters.Add("location", targetFolder);

            //string[] keys = parameters.AllKeys;
            //StringBuilder HashStringBuilder = new StringBuilder();
            //Array.Sort(keys);

            //foreach (string key in keys)
            //{
            //    HashStringBuilder.Append(key);
            //    HashStringBuilder.Append(parameters[key]);
            //    sb.Append("--" + boundary + "\r\n");
            //    sb.Append("Content-Disposition: form-data; name=\"" + key + "\"\r\n");
            //    sb.Append("\r\n");
            //    sb.Append(parameters[key] + "\r\n");
            //}

            //sb.Append("--" + boundary + "\r\n");
            //sb.Append("Content-Disposition: form-data; name=\"sendfile\"; filename=\"" + localFile + "\"\r\n");
            //sb.Append("Content-Type: " + ResolveMimeType(localFile) + "\r\n");
            //sb.Append("\r\n");

            //UTF8Encoding encoding = new UTF8Encoding();

            //byte[] postContents = encoding.GetBytes(sb.ToString());

            //FileStream fstream = new FileStream(localFile, FileMode.Open);
            //byte[] photoContents = new byte[fstream.Length];
            //fstream.Read(photoContents, 0, photoContents.Length);
            //fstream.Close();

            //byte[] postFooter = encoding.GetBytes("\r\n--" + boundary + "--\r\n");

            //byte[] dataBuffer = new byte[postContents.Length + photoContents.Length + postFooter.Length];
            //Buffer.BlockCopy(postContents, 0, dataBuffer, 0, postContents.Length);
            //Buffer.BlockCopy(photoContents, 0, dataBuffer, postContents.Length, photoContents.Length);
            //Buffer.BlockCopy(postFooter, 0, dataBuffer, postContents.Length + photoContents.Length, postFooter.Length);

            //req.ContentLength = dataBuffer.Length;

            //Stream reqStream = req.GetRequestStream();

            //int uploadBit = Math.Max(dataBuffer.Length / 100, 50 * 1024);
            //int uploadSoFar = 0;

            //for (int i = 0; i < dataBuffer.Length; i = i + uploadBit)
            //{
            //    int toUpload = Math.Min(uploadBit, dataBuffer.Length - i);
            //    uploadSoFar += toUpload;

            //    reqStream.Write(dataBuffer, i, toUpload);

            //    TransferChunk(dataBuffer.Length, i + toUpload);

            //    //if ((OnUploadProgress != null) && ((j++) % 5 == 0 || uploadSoFar == dataBuffer.Length))
            //    //{
            //    //    OnUploadProgress(this, new UploadProgressEventArgs(i + toUpload, uploadSoFar == dataBuffer.Length));
            //    //}
            //}
            //reqStream.Close();

            //HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            //Stream resStream = res.GetResponseStream();
            //resStream.Close();
            //res.Close();
        }

        public void DeleteFile(BoxNetFs deleteItem)
        {
            sendXmlDoc = new XmlDocument();
            sendXmlDoc.LoadXml("<xml></xml>");

            XmlNode root = sendXmlDoc.DocumentElement;
            XmlElement action = sendXmlDoc.CreateElement("action");
            XmlText actiontxt = sendXmlDoc.CreateTextNode("delete");

            XmlElement xmlTarget = sendXmlDoc.CreateElement("target");
            XmlText xmlTTargetType;

            //if (deleteItem.FileId!="")
            if (deleteItem.ItemType == FileSystemType.FileType)
                xmlTTargetType = sendXmlDoc.CreateTextNode("file");
            else
                xmlTTargetType = sendXmlDoc.CreateTextNode("folder");

            XmlNode xmlItemId = sendXmlDoc.CreateElement("item_id");
            XmlText xmlTItemId = sendXmlDoc.CreateTextNode(deleteItem.ItemId);

            XmlNode xmlData = sendXmlDoc.CreateElement("data");

            root.AppendChild(action);
            action.AppendChild(actiontxt);

            root.AppendChild(xmlData);
            xmlData.AppendChild(xmlTarget);
            xmlTarget.AppendChild(xmlTTargetType);

            xmlData.AppendChild(xmlItemId);
            xmlItemId.AppendChild(xmlTItemId);

            comm.UploadString = sendXmlDoc.InnerXml;
            comm.Url = this.BaseUrl + sid;

            comm.SendReceive();
            rcvXmlDoc.LoadXml(comm.Response);
        }

        public bool CreateFolder(BoxNetFs bnCreate)
        {
            sendXmlDoc = new XmlDocument();
            sendXmlDoc.LoadXml("<xml></xml>");

            XmlNode root = sendXmlDoc.DocumentElement;
            XmlElement action = sendXmlDoc.CreateElement("action");
            XmlText actiontxt = sendXmlDoc.CreateTextNode("create_folder");

            XmlNode data = sendXmlDoc.CreateElement("data");

            root.AppendChild(action);
            action.AppendChild(actiontxt);
            root.AppendChild(data);

            XmlNode folder = sendXmlDoc.CreateElement("folder");
            data.AppendChild(folder);

            XmlNode parent = sendXmlDoc.CreateElement("parent_id");
            XmlText parent_id = sendXmlDoc.CreateTextNode(bnCreate.FolderId);
            folder.AppendChild(parent);
            parent.AppendChild(parent_id);

            XmlNode name = sendXmlDoc.CreateElement("name");
            XmlText name_text = sendXmlDoc.CreateTextNode(bnCreate.Name);
            folder.AppendChild(name);
            name.AppendChild(name_text);

            XmlNode sharing = sendXmlDoc.CreateElement("sharing");
            folder.AppendChild(sharing);

            XmlNode share = sendXmlDoc.CreateElement("share");
            XmlText share_value = sendXmlDoc.CreateTextNode("ignore");
            sharing.AppendChild(share);
            share.AppendChild(share_value);

            XmlNode p_comments = sendXmlDoc.CreateElement("p_comments");
            XmlText p_comments_value = sendXmlDoc.CreateTextNode("1");
            sharing.AppendChild(p_comments);
            p_comments.AppendChild(p_comments_value);

            XmlNode a_password = sendXmlDoc.CreateElement("a_password");
            XmlText a_password_value = sendXmlDoc.CreateTextNode("");
            sharing.AppendChild(a_password);
            a_password.AppendChild(a_password_value);

            XmlNode send_to = sendXmlDoc.CreateElement("send_to");
            XmlText send_to_value = sendXmlDoc.CreateTextNode("");
            sharing.AppendChild(send_to);
            send_to.AppendChild(send_to_value);

            XmlNode e_message = sendXmlDoc.CreateElement("e_message");
            XmlText e_message_text = sendXmlDoc.CreateTextNode("");
            sharing.AppendChild(e_message);
            e_message.AppendChild(e_message_text);

            XmlNode type_id = sendXmlDoc.CreateElement("type_id");
            XmlText type_id_value = sendXmlDoc.CreateTextNode("");
            sharing.AppendChild(type_id);
            type_id.AppendChild(type_id_value);


            comm.UploadString = sendXmlDoc.InnerXml;
            comm.Url = this.BaseUrl + sid;
            comm.SendReceive();
            rcvXmlDoc.LoadXml(comm.Response);

            XmlNodeList status = rcvXmlDoc.GetElementsByTagName("status");

            if (status.Count > 0)
            {
                if (status[0].InnerText == "\ncreate_ok\n")
                    return true;
            }
            return false;
        }

        public bool Register()
        {
            sendXmlDoc = new XmlDocument();
            sendXmlDoc.LoadXml("<xml></xml>");

            XmlNode root = sendXmlDoc.DocumentElement;
            XmlElement action = sendXmlDoc.CreateElement("action");
            XmlText actiontxt = sendXmlDoc.CreateTextNode("register");

            XmlElement xmlEmail = sendXmlDoc.CreateElement("email");
            XmlText xmlTEmail = sendXmlDoc.CreateTextNode(UserName);

            XmlNode xmlPassword = sendXmlDoc.CreateElement("password");
            XmlText xmlTPassword = sendXmlDoc.CreateTextNode(PassWord);

            XmlNode xmlData = sendXmlDoc.CreateElement("data");

            root.AppendChild(action);
            action.AppendChild(actiontxt);

            root.AppendChild(xmlData);
            xmlData.AppendChild(xmlEmail);
            xmlEmail.AppendChild(xmlTEmail);

            xmlData.AppendChild(xmlPassword);
            xmlPassword.AppendChild(xmlTPassword);

            comm.UploadString = sendXmlDoc.InnerXml;
            comm.Url = this.BaseUrl + sid;
            comm.SendReceive();
            rcvXmlDoc.LoadXml(comm.Response);

            XmlNodeList status = rcvXmlDoc.GetElementsByTagName("status");

            if (status.Count > 0)
            {
                if (status[0].InnerText == "successful_register")
                    return true;
            }
            return false;
        }

        public void Rename(BoxNetFs bnFS, string new_name_string)
        {
            sendXmlDoc = new XmlDocument();
            sendXmlDoc.LoadXml("<xml></xml>");

            XmlNode root = sendXmlDoc.DocumentElement;
            XmlElement action = sendXmlDoc.CreateElement("action");
            XmlText actiontxt = sendXmlDoc.CreateTextNode("rename");

            XmlNode data = sendXmlDoc.CreateElement("data");

            root.AppendChild(action);
            action.AppendChild(actiontxt);
            root.AppendChild(data);

            XmlNode target = sendXmlDoc.CreateElement("target");
            XmlText target_value;
            //if (bnFS.GetType() == typeof(BoxNetFile))
            if (bnFS.ItemType == FileSystemType.FileType)
            {
                target_value = sendXmlDoc.CreateTextNode("file");
            }
            else
            {
                target_value = sendXmlDoc.CreateTextNode("folder");
            }

            data.AppendChild(target);
            target.AppendChild(target_value);

            XmlNode item_id = sendXmlDoc.CreateElement("item_id");
            XmlText item_id_text = sendXmlDoc.CreateTextNode(bnFS.ItemId);

            data.AppendChild(item_id);
            item_id.AppendChild(item_id_text);

            XmlNode new_name = sendXmlDoc.CreateElement("new_name");
            XmlText new_name_text = sendXmlDoc.CreateTextNode(new_name_string);
            data.AppendChild(new_name);
            new_name.AppendChild(new_name_text);

            comm.UploadString = sendXmlDoc.InnerXml;
            comm.Url = this.BaseUrl + sid;
            comm.SendReceive();
            rcvXmlDoc.LoadXml(comm.Response);
        }

        public void DownloadFileThreaded(BoxNetFs file)
        {
            if (!transferring)
            {
                fileid = file.FileId;
                filename = file.FileName;
                filesize = long.Parse(file.Size);
                downloadThread = new Thread(downloadThreaded);
                downloadThread.IsBackground = true;
                downloadThread.Start();
            }
            else
            {
                AlreadyTranferring();
            }
        }

        void downloadThreaded()
        {
            transferring = true;
            comm.DownloadFile(DownloadPath + filename,
                string.Format("http://www.box.net/ping/download/{0}/{1}", fileid, sid), this.filesize);
            transferring = false;
            //DownloadComplete();
        }

        public void AbortDownload()
        {
            if (transferring)
            {
                downloadThread.Abort();
            }
        }
    }
}